import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import classNames from 'classnames';
import {immutableRenderDecorator} from 'react-immutable-render-mixin';
import CSSModules from 'react-css-modules';
import {Motion, spring} from 'react-motion';
import styles from './tab.module.scss';
import InkBar from './InkBar';

function getOuterWidth (el) {
  return el.offsetWidth;
}

function getOffset (el) {
  const html = el.ownerDocument.documentElement;
  const box = el.getBoundingClientRect();

  return {
    top: box.top + window.pageYOffset - html.clientTop,
    left: box.left + window.pageXOffset - html.clientLeft
  };
}

@immutableRenderDecorator
@CSSModules(styles, {allowMultiple: true})

class TabNav extends Component {
  constructor (props) {
    super(props);

    this.state = {
      inkBarWidth: 0,
      inkBarLeft: 0
    };
  }

  componentDidMount () {
    const {activeIndex} = this.props;
    const node = ReactDOM.findDOMNode(this);
    const el = node.querySelectorAll('li')[activeIndex];

    this.setState({
      inkBarWidth: getOuterWidth(el),
      inkBarLeft: getOffset(el).left
    });
  }

  componentDidUpdate (prevProps) {
    if (prevProps.activeIndex !== this.props.activeIndex) {
      const {activeIndex} = this.props;
      const node = ReactDOM.findDOMNode(this);
      const el = node.querySelectorAll('li')[activeIndex];

      this.setState({
        inkBarWidth: getOuterWidth(el),
        inkBarLeft: getOffset(el).left
      });
    }
  }

  getTabs () {
    const {panels, activeIndex} = this.props;
    const rst = [];

    return panels.map(child => {
      if (!child) return;
      const order = parseInt(child.props.order, 10);

      let classes = classNames({
        tab: true,
        tabActive: activeIndex === order,
        disabled: child.props.disabled
      });

      let events = {};
      if (!child.props.disabled) {
        events = {
          onClick: this.props.onTabClick.bind(this, order)
        };
      }

      const ref = {};
      if (activeIndex === order) {
        ref.ref = 'activeTab';
      }
      return (
        <li
          {...events}
          styleName={classes}
          key={order}
          {...ref}
        >
          {child.props.tab}
        </li>
      )
    })
  }

  render () {
    const {activeIndex} = this.props;

    const rootClasses = classNames({
      bar: true
    });

    const classes = classNames({
      nav: true
    });

    return (
      <div styleName={rootClasses}>
        <Motion style={{left: spring(this.state.inkBarLeft)}}>
          {
            ({left}) => (
              <InkBar width={this.state.inkBarWidth} left={left}></InkBar>
            )
          }
        </Motion>
        <ul styleName={classes}>
          {this.getTabs()}
        </ul>
      </div>
    );
  }
}

export default TabNav;